<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        :key="showFormKey">
        <!-- 流程名 -->
        <el-col :span="24" v-if="hasFormPermission('process_name')">
          <el-form-item :label="$t('流程名')" prop="process_name">
            <el-input v-model="formData['process_name']" placeholder="请输入流程名"
              :disabled="hasDisabledPermission('process_name',false)"
              :readonly="!hasEditPermission('process_name',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- 流程定义KEY -->
        <el-col :span="24" v-if="hasFormPermission('process_def_key')">
          <el-form-item :label="$t('流程定义KEY')" prop="process_def_key">
            <el-input v-model="formData['process_def_key']" placeholder="请输入流程定义KEY"
              :disabled="hasDisabledPermission('process_def_key',false)"
              :readonly="!hasEditPermission('process_def_key',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- 展示字段KEY -->
        <el-col :span="24" v-if="hasFormPermission('filed_key')">
          <el-form-item :label="$t('展示字段KEY')" prop="filed_key">
            <el-input v-model="formData['filed_key']" placeholder="请输入展示字段KEY"
              :disabled="hasDisabledPermission('filed_key',false)"
              :readonly="!hasEditPermission('filed_key',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- 展示字段标题 -->
        <el-col :span="24" v-if="hasFormPermission('file_title')">
          <el-form-item :label="$t('展示字段标题')" prop="file_title">
            <el-input v-model="formData['file_title']" placeholder="请输入展示字段标题"
              :disabled="hasDisabledPermission('file_title',false)"
              :readonly="!hasEditPermission('file_title',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- 是否列表 -->
        <el-col :span="24" >
          <el-form-item :label="$t('是否列表')">
               <el-radio v-model="formData['is_list']" :label="1">是</el-radio>
              <el-radio v-model="formData['is_list']" :label="0">否</el-radio>
          </el-form-item>
        </el-col>
        <!-- 排序 -->
        <el-col :span="24" >
          <el-form-item :label="$t('排序')">
            <el-input placeholder="请输入排序" v-model.number="formData['sort_code']" ></el-input>
          </el-form-item>
        </el-col>
        <!-- 是否开启展示条件 -->
        <el-col :span="24" >
          <el-form-item :label="$t('是否开启展示条件')">
               <el-radio v-model="formData['enable_show_condition']" :label="1">是</el-radio>
              <el-radio v-model="formData['enable_show_condition']" :label="0">否</el-radio>
          </el-form-item>
        </el-col>
        <!-- 条件字段名称 -->
        <el-col :span="24" >
          <el-form-item :label="$t('条件字段名称')">
            <el-input placeholder="请输入排序" v-model.number="formData['condition_column_name']" ></el-input>
          </el-form-item>
        </el-col>
        <!-- 条件字段值 -->
        <el-col :span="24" >
          <el-form-item :label="$t('条件字段值')">
            <el-input placeholder="请输入排序" v-model.number="formData['condition_column_value']" ></el-input>
          </el-form-item>
        </el-col>
        <!-- 类型 -->
        <!-- 类型 10: 字段, 20: 表单, 30: 列表, 40: 流程信息, 50: 文件：type -->
        <el-col :span="24" >
          <el-form-item :label="$t('类型')">
              <el-radio v-model="formData['type']" label="10">字段</el-radio>
              <el-radio v-model="formData['type']" label="20">表单</el-radio>
              <el-radio v-model="formData['type']" label="30">列表</el-radio>
              <el-radio v-model="formData['type']" label="40">流程信息</el-radio>
              <el-radio v-model="formData['type']" label="50">文件</el-radio>
          </el-form-item>
        </el-col>

        <!-- 父id -->
        <el-col :span="24" >
          <el-form-item :label="$t('父id')">
            <el-input placeholder="请输入排序" v-model="formData['p_id']" ></el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="24" v-if="!isWorkflowForm">
          <el-form-item size="large" v-if="isEdit">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import FilterableDataList from '@/components/generator/clientComponents/FilterableDataList.vue';
        import workflowFormAuthorize from "@/mixins/workflowFormAuthorize";
        import authorizeMixin from "@/mixins/authorize";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
        export default {
          mixins: [authorizeMixin,workflowFormAuthorize],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    let _this = this
    return {
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
      addressUrl:'filedshowconfig',
      mainTableName: 'process_show_filed_config',
      formConfig: {},
      formData: {
        'process_name': '',
        'process_def_key': '',
        'filed_key': '',
        'file_title': '',
        'is_list':1,
        'sort_code':0,
        'enable_show_condition':0,//是否开启展示条件：
        'condition_column_name':'',//条件字段名称
        'condition_column_value':'',//条件字段值
        'type':0,//类型, 10: 字段, 20: 表单, 30: 列表, 40: 流程信息, 50: 文件
        'p_id':'',//父id
      },
      rules: {
        process_name: [{
          required: true,
          message: '请输入流程名',
          trigger: 'blur'
        }],
        process_def_key: [{
          required: true,
          message: '请输入流程定义KEY',
          trigger: 'blur'
        }],
        filed_key: [{
          required: true,
          message: '请输入展示字段KEY',
          trigger: 'blur'
        }],
        file_title: [{
          required: true,
          message: '请输入展示字段标题',
          trigger: 'blur'
        }],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.formConfig = this.getFormConfig();
  },
  async mounted() {
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data
            
                 this.showFormKey++;
              } catch (error) {
              }
          }

       
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
      };
    },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
    async aysncValidateForm() {
      let validataArry = []
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate(valid => {
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {},
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();
      
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
      
    },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助工作流 审批(编辑) 预留方法
          handleEdit() {
          },
          
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList[bindTable] != undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList[bindTable] != undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    getFormConfig() {
      let config = {
        "fields": [{
          "__vModel__": "process_name",
          "__config__": {
            "label": "流程名",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input-tip",
            "required": true,
            "span": 24,
            "F_LgMarkCode": "",
            "prestrainField": "",
            "formId": 103,
            "fieldLength": 500,
            "bindTable": "process_show_filed_config",
            "bindTableField": "process_name",
            "bindTableFieldType": "varchar"
          }
        }, {
          "__vModel__": "process_def_key",
          "__config__": {
            "label": "流程定义KEY",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input-tip",
            "required": true,
            "span": 24,
            "F_LgMarkCode": "",
            "prestrainField": "",
            "formId": 100,
            "fieldLength": "200",
            "bindTable": "process_show_filed_config",
            "bindTableField": "process_def_key",
            "bindTableFieldType": "varchar"
          }
        }, {
          "__vModel__": "filed_key",
          "__config__": {
            "label": "展示字段KEY",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input-tip",
            "required": true,
            "span": 24,
            "F_LgMarkCode": "",
            "prestrainField": "",
            "formId": 101,
            "fieldLength": "200",
            "bindTable": "process_show_filed_config",
            "bindTableField": "filed_key",
            "bindTableFieldType": "varchar"
          }
        }, {
          "__vModel__": "file_title",
          "__config__": {
            "label": "展示字段标题",
            "showLabel": true,
            "tag": "el-input",
            "avueType": "input-tip",
            "required": true,
            "span": 24,
            "F_LgMarkCode": "",
            "prestrainField": "",
            "formId": 102,
            "fieldLength": "300",
            "bindTable": "process_show_filed_config",
            "bindTableField": "file_title",
            "bindTableFieldType": "varchar"
          }
        }]
      };
      return config;
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

</style>
